package com.free.execute;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

/**
 * System command executor.
 * 
 * @author YongXia.
 * 
 * @since jdk1.6
 * @version 1.0
 * 
 */
public class Executor {
    private static final String ERROR_STREAM = "ERRORSTREAM";

    private static final String INPUT_STREAM = "INPUTSTREAM";

    private static Executor instance;

    /**
     * Execute the system command.
     * 
     * @author YongXia.
     * 
     * @since jdk1.6
     * @version 1.0
     * 
     * @param command
     *            the command.
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static String exec(final String command) throws IOException, InterruptedException {
        StringBuilder result = null;
        if (StringUtils.isNotBlank(command)) {
            Process process = Runtime.getRuntime().exec(command);
            ReadThread infoReadThread = new ReadThread(process.getInputStream(), Executor.INPUT_STREAM);
            ReadThread errReadThread = new ReadThread(process.getErrorStream(), Executor.ERROR_STREAM);
            infoReadThread.start();
            errReadThread.start();
            while (!infoReadThread.flag || !errReadThread.flag)
                Thread.sleep(100);
            result = new StringBuilder(command);
            String s = infoReadThread.getResult();
            if (null != s)
                result.append("\nINFO:[\n").append(s).append("]");
            s = errReadThread.getResult();
            if (null != s)
                result.append("\nERROR:[\n").append(s).append("]");
            s = null;
            process = null;
            infoReadThread = null;
            errReadThread = null;
        }
        return result.toString();
    }

    public static void main(final String[] args) {
        String command = "";
        for (String arg : args)
            command += arg + " ";
        try {
            String result = Executor.exec(command);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private Executor() {
    }

    /**
     * Get an Executor instance.
     * 
     * @author YongXia.
     * 
     * @since jdk1.6
     * @version 1.0
     * 
     * @return
     */
    public synchronized Executor getInstance() {
        if (null == Executor.instance)
            Executor.instance = new Executor();
        return Executor.instance;
    }
}
